package com.crm.util;

import java.security.MessageDigest;
import java.sql.Date;
import java.text.SimpleDateFormat;

import org.apache.log4j.Logger;

public class StringEx {

	private static Logger logger = Logger.getLogger(StringEx.class);
	
	public static SimpleDateFormat formatCommon = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static SimpleDateFormat formatLong = new SimpleDateFormat("yyyyMMddHHmmss");
	public static SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
	
	public static String valueOf(String value){
		return value != null && value.trim().length() > 0 ? value: "";
	}
	
	public static String valueOfTrim(String value){
		return valueOf(value).trim();
	}
	
	public static String valueOfTrim(String value, String defaultValue){
		String temp = valueOfTrim(value);
		return temp.length() > 0 ? temp : defaultValue;
	}
	
	public static String valueOf(Double value){
		return value != null ? String.valueOf(value): "0.00";
	}
	
	public static String valueOf(Integer value){
		return value != null ? String.valueOf(value): "0";
	}
	
	public static String valueOf(Date value){
		return value != null ? formatCommon.format(value) : "";
	}
	
	public static String valueOf(Date value, SimpleDateFormat format){
		return value != null ? format.format(value) : "";
	}
	
	public static String valueOfLongDate(Long value){
		try {
			return value != null ? formatCommon.format(formatLong.parse(String.valueOf(value))) : "";
		} catch (Exception e) {
			logger.error(e);
		}
		return "";
	}
	
	public static Date getSqlDate(String value){
		return value != null && value.trim().length() > 0 ? Date.valueOf(value): null;
	}
	
	public static java.util.Date getUtilDate(String value){
		java.util.Date tempDate = null;
		try {
			tempDate = value != null && value.trim().length() > 0 ? formatCommon.parse(value): null;
		} catch (Exception e) {
			logger.error(e);
			return null;
		}
		return tempDate;
	}
	
	public static String encodeByMD5(String value){
		if(value == null){
			return "";
		}
		char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};       
        try {
            byte[] btInput = value.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
        	logger.error(e);
            return "";
        }
	}
	
	public static void main(String[] args) {		
		System.out.println(encodeByMD5(null));
	}

}
